<template>
  <div class="row inner-form">
    <div class="col">
      <div class="title-bar" style="margin-left: -15px ;margin-right: -15px;">
        <span>{{title}}</span>
      </div>
      <div class="form-content mt-15">
        <el-form :model="form" :rules="rules" ref="form" class="custom-form">
          <el-form-item label="实际单号:" prop="orderSn">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-input v-model="form.orderSn" clearable placeholder="输入实际采购单号"></el-input>
              </el-col>
              <el-col :span="11">
                <span>请填写实际的采购单号,如果没有请自定义一个唯一编码</span>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="供应商:" prop="supplierId">
            <el-row :gutter="20">
              <el-col :span="8">
                <h-supply-choose v-model="form.supplierId"></h-supply-choose>
              </el-col>
              <el-col :span="11">
                <span>请选择供应商</span>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="采购日期:" prop="orderDate">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-date-picker
                  v-model="form.orderDate"
                  type="date"
                  placeholder="选择采购日期"
                  format="yyyy-MM-dd"
                  value-format="yyyyMMdd"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </el-col>
              <el-col :span="11">
                <span>请选择采购的日期</span>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="采购数量:" prop="orderNum">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-input-number v-model="form.orderNum" :min="0"></el-input-number>
              </el-col>
              <el-col :span="11">
                <span>输入采购物品的总数量</span>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="货币类型:" required>
            <el-row :gutter="20">
              <el-col :span="8">
                <h-currency-select v-model="form.currencyId"></h-currency-select>
              </el-col>
              <el-col :span="11">
                <span>请选择订单的货币类型</span>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="采购金额:" prop="orderPrice">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-input-number :step="0.01" v-model="form.orderPrice"></el-input-number>
              </el-col>
              <el-col :span="11">
                <span>请输入原始货币的订单金额</span>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="售出汇率:" prop="exchangeRate">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-input-number :step="0.0001" v-model="form.exchangeRate"></el-input-number>
              </el-col>
              <el-col :span="11">
                <span>请输入售出的汇率</span>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="外币运费:" prop="globalFreight">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-input-number :step="0.01" v-model="form.globalFreight"></el-input-number>
              </el-col>
              <el-col :span="11">
                <span>请输入外币结算的运费。</span>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="运费:" prop="freight">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-input-number :step="0.01" v-model="form.freight"></el-input-number>
              </el-col>
              <el-col :span="11">
                <span>请输入人民币表示的运费</span>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="结算汇率:" prop="closeExchangeRate">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-input-number :step="0.0001" v-model="form.closeExchangeRate"></el-input-number>
              </el-col>
              <el-col :span="11">
                <span>请输入结算汇率</span>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="结算总额:">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-input-number :step="0.0001" v-model="price"></el-input-number>
              </el-col>
              <el-col :span="11">
                <span class="red">结算总额=订单金额*结算汇率+国际运费*结算汇率+国内运费。</span>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="备注:" prop="note">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-input type="textarea" v-model="form.note" placeholder="请输入备注信息"></el-input>
              </el-col>
              <el-col :span="11">
                <span>请填写采购单的备注信息</span>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <div class="row">
          <div class="col">
            <div class="col">
              <el-button type="primary" v-if="type==1" :loading="doLoading" @click="saveForm"><i class="fa fa-plus"></i>
                添加采购单
              </el-button>
              <el-button type="primary" v-if="type==2" :loading="doLoading" @click="saveForm"><i class="fa fa-save"></i>
                保存采购单
              </el-button>
              <el-button type="success" @click="goback"><i class="fa fa-sign-out"></i> 返回</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import FormMix from 'src/components/common/js/form-mix'
  import HCurrencySelect from 'src/components/common/select/HCurrencySelect'
  import AdminService from 'src/service/admin'
  import HSupplyChoose from 'src/components/common/choose/HSupplyChoose'

  export default {
    name: 'HPurchaseEdit',
    mixins: [FormMix],
    components: {HCurrencySelect, HSupplyChoose},
    data() {
      return {
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }]
        },

        form: {},
        title: '添加采购单',
        type: 1, //1 创建 2 编辑
        doLoading: false,
        rules: {
          orderSn: [
            {required: true, message: '请输入实际订单号', trigger: 'blur'}
          ],
          orderDate: [
            {required: true, message: '请输入采购日期', trigger: 'blur'}
          ],
          supplierId: [
            {required: true, message: '请选择供应商', trigger: 'change'}
          ],
          exchangeRate: [
            {required: true, message: '请输入售出汇率', trigger: 'blur'}
          ],
          orderPrice: [
            {required: true, message: '请输入订单金额', trigger: 'blur'}
          ],
          currency: [
            {required: true, message: '请输入货币类型', trigger: 'blur'}
          ],
          orderNum: [
            {required: true, message: '请输入采购数量', trigger: 'blur'}
          ],
          closeExchangeRate: [
            {required: true, message: '请输入结算汇率', trigger: 'blur'}
          ]
        }
      }
    },
    computed: {
      price: {
        get: function () {
          this.form.cost = this.form.orderPrice * this.form.closeExchangeRate +
            this.form.globalFreight * this.form.closeExchangeRate + this.form.freight
          return this.form.cost.toFixed(2)
        },
        set: function (newValue) {

        }
      }
    },
    methods: {
      dateFtt: function (fmt, date) { //author: meizz
        var o = {
          "M+": date.getMonth() + 1,                 //月份
          "d+": date.getDate(),                    //日
          "h+": date.getHours(),                   //小时
          "m+": date.getMinutes(),                 //分
          "s+": date.getSeconds(),                 //秒
          "q+": Math.floor((date.getMonth() + 3) / 3), //季度
          "S": date.getMilliseconds()             //毫秒
        };
        if (/(y+)/.test(fmt))
          fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
          if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
      },
      saveForm: function () {
        const me = this

        me.$refs['form'].validate((valid) => {
          if (valid) {
            me.doLoading = true
            AdminService.purchase(me.form).then(function (data) {
              if (data != null) {
                const purchase = data.datas[0]
                me.$router.push('/admin/purchase/purchases/' + purchase.id + '/detail.html')
                setTimeout(function () {
                  if (me.type == 1) {
                    me.$message.success('采购单创建成功。')
                  } else {
                    me.$message.success('保存采购单成功。')
                  }
                }, 200)
              }
              me.doLoading = false
            })
          } else {
            return false
          }
        })

      },
      getData: function (id) {
        const me = this
        AdminService.purchaseById(id).then(ds => {
          if (ds != null) {
            const data = ds.datas[0]
            me.form = {
              id: data.id,
              orderSn: data.orderSn,
              supplierId: data.supply.id,
              currencyId: data.currency.id,
              orderDate: data.orderDate.replace(/-/g, ''),
              orderNum: data.orderNum,
              orderPrice: data.orderPrice,
              exchangeRate: data.exchangeRate,
              closeExchangeRate: data.closeExchangeRate,
              cost: data.cost,
              freight: data.freight,
              note: data.note,
              globalFreight: data.globalFreight

            }
          }
        })
      },
      goback: function () {
        this.$router.go(-1)
      }
    },
    beforeMount: function () {
      if (this.$route.meta.type === 'edit') {
        this.type = 2
        this.title = '编辑采购单'
        this.getData(this.$route.params.id)
      } else {
        this.type = 1
        this.title = '添加采购单'
        this.form = {
          orderSn: '',
          supplierId: null,
          currencyId: 6,
          orderDate: this.dateFtt('yyyyMMdd', new Date()),
          orderNum: 0,
          orderPrice: 0,
          exchangeRate: 0,
          closeExchangeRate: 0,
          cost: 0,
          freight: 0,
          note: '',
          globalFreight: 0
        }
      }
    }
  }
</script>
